//
//  ExpectedIndustryVC.m
//  MyProject
//
//  Created by 石小强 on 2018/3/29.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "ExpectedIndustryVC.h"
#import "ExpectedIndustryLeftCell.h"
#import "ExpectedIndustryRightCell.h"
#import "IndustryModel.h"
#import "JobModel.h"
#import "ExpectIndustryDeleteView.h"

@interface ExpectedIndustryVC ()

@property (nonatomic, strong) NSMutableArray *leftDatas;
@property (nonatomic, strong) NSMutableArray *rightDatas;

@property (nonatomic, strong) NSMutableArray *selectedRightDatas;

@end

@implementation ExpectedIndustryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    
    [self setupSubViews];
    
    // 获取行业信息
    [self loadIndustriesData];
}

/** 获取行业信息 */
- (void)loadIndustriesData {
    WS(weakSelf)
    [self showProgressWithView:self.view animated:YES];
    [SendRequest getIndustriesWithResult:^(NSDictionary *result, NSError *error) {
        [weakSelf hideProgress:self.view animated:YES];
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1)
        {
            SaintiLog(@"获取行业信息--返回值 = %@", result);
            [weakSelf.leftDatas removeAllObjects];
            
            NSArray *datas = [IndustryModel mj_objectArrayWithKeyValuesArray:[result objectForKey:@"data"]];
            [weakSelf.leftDatas addObjectsFromArray:datas];
            if (datas.count > 0) {
                IndustryModel *first = [datas objectAtIndex:0];
                [weakSelf loadIndustryListWithIndustryId:first.industryId];
            }
            [weakSelf.leftTableView reloadData];
            
            if (datas.count > 0) {
                NSIndexPath *leftIP = [NSIndexPath indexPathForRow:0 inSection:0];
                [self.leftTableView selectRowAtIndexPath:leftIP animated:NO scrollPosition:UITableViewScrollPositionTop];
            }
            
        }else{
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}


/** 获取职位 */
- (void)loadIndustryListWithIndustryId:(NSString *)industryId {
    WS(weakSelf)
    [self showProgressWithView:self.view animated:YES];
    [SendRequest getIndustriesWithIndustryId:industryId result:^(NSDictionary *result, NSError *error) {
        [weakSelf hideProgress:self.view animated:YES];
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1)
        {
            SaintiLog(@"获取职位1--返回值 = %@", result);
            NSArray *datas = [IndustryModel mj_objectArrayWithKeyValuesArray:[result objectForKey:@"data"]];
            [weakSelf.rightDatas removeAllObjects];
            [weakSelf.rightDatas addObjectsFromArray:datas];
            
            [weakSelf.rightTableView reloadData];
            if (weakSelf.rightDatas.count > 0) {
                NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:0];
                [weakSelf.rightTableView selectRowAtIndexPath:ip animated:NO scrollPosition:UITableViewScrollPositionTop];
            }
        }else{
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

- (void)setupNav {
    self.navigationItem.title = @"期望行业";
    
    CGSize titleS = [Tool sizeWithText:@"完成" font:[UIFont systemFontOfSize:13]];
    UIButton *complete = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, titleS.width, 44)];
    [complete setTitle:@"完成" forState:UIControlStateNormal];
    complete.titleLabel.font = [UIFont systemFontOfSize:13];
    [complete setTitleColor:UIColorFromRGB(0x373B3C) forState:UIControlStateNormal];
    [complete addTarget:self action:@selector(completeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:complete];
}

- (void)completeBtnClick {
    self.industryBlock(self.selectedRightDatas);
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupSubViews {
    [self.leftTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ExpectedIndustryLeftCell class]) bundle:nil] forCellReuseIdentifier:@"ExpectedIndustryLeftCell"];
    [self.rightTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ExpectedIndustryRightCell class]) bundle:nil] forCellReuseIdentifier:@"ExpectedIndustryRightCell"];
    
    if (self.jobs && self.jobs.count > 0) {
        [self.selectedRightDatas removeAllObjects];
        [self.selectedRightDatas addObjectsFromArray:self.jobs];
        [self setTopView];
    }
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.leftTableView) {
        return self.leftDatas.count;
    } else {
        return self.rightDatas.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.leftTableView) {
        ExpectedIndustryLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExpectedIndustryLeftCell"];
        IndustryModel *industry = [self.leftDatas objectAtIndex:indexPath.row];
        cell.nameL.text = industry.industryName;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        ExpectedIndustryRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExpectedIndustryRightCell"];
        IndustryModel *job = [self.rightDatas objectAtIndex:indexPath.row];
        cell.nameL.text = job.industryName;
        cell.isSelect = [self checkInSelectDatas:job] ? 1 : 0;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.rightTableView) {
        IndustryModel *industry = [self.rightDatas objectAtIndex:indexPath.row];
        
        NSInteger count = self.selectedRightDatas.count;
        
        if (count >= 3) {
            if (industry.isSelect == 0) {
                [CommonUtils showToast:@"最多选择3个行业"];
            } else {
                industry.isSelect = 0;
                if ([self checkInSelectDatas:industry]) {  // 删除此jobModel
                    self.selectedRightDatas = [self deleteJobModel:industry];
                }
                [tableView reloadData];
                [self setTopView];
            }
        } else {
            industry.isSelect = industry.isSelect == 0 ? 1 : 0;
            if (industry.isSelect == 1) {
                if ([self checkInSelectDatas:industry]) {
                    //
                } else {
                    [self.selectedRightDatas addObject:industry];
                }
            } else {
                if ([self checkInSelectDatas:industry]) {  // 删除此Model
                    self.selectedRightDatas = [self deleteJobModel:industry];
                }
            }
            [tableView reloadData];
            [self setTopView];
        }
    } else {
        IndustryModel *industry = [self.leftDatas objectAtIndex:indexPath.row];
        [self loadIndustryListWithIndustryId:industry.industryId];
        [self.rightDatas removeAllObjects];
        [tableView reloadData];
        [self.leftTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
}

- (BOOL)checkInSelectDatas:(IndustryModel *)job {
    for (NSInteger i = 0; i < self.selectedRightDatas.count; i++) {
        IndustryModel *jobM = [self.selectedRightDatas objectAtIndex:i];
        if ([job.industryId isEqualToString:jobM.industryId]) {
            return YES;
            break;
        }
    }
    return NO;
}

- (void)setTopView {
    CGFloat MaxWidth = kScreenWidth - 90;
    
    // 清除以前的子控件
    for (UIView *con in self.topView.subviews) {
        [con removeFromSuperview];
    }
    
    CGFloat topViewHeight = 40;
    CGFloat itemX = 15;
    CGFloat itemY = 10;
    for (NSInteger i = 0; i < self.selectedRightDatas.count; i++) {
        IndustryModel *industrly = [self.selectedRightDatas objectAtIndex:i];
        CGFloat itemW = [Tool sizeWithText:industrly.industryName font:[UIFont fontWithName:@"PingFang SC" size:12]].width + 38;
        
        if (itemX + itemW + 7 >= MaxWidth) {
            itemX = 15;
            itemY += 30;
            topViewHeight += 30;
        }
        
//        ExpectIndustryDeleteView *deleteV = [[ExpectIndustryDeleteView alloc] initWithFrame:CGRectMake(itemX, itemY, itemW, 20) andJobModel:industrly];
        ExpectIndustryDeleteView *deleteV = [[ExpectIndustryDeleteView alloc] initWithFrame:CGRectMake(itemX, itemY, itemW, 20) andIndustryModel:industrly];
        deleteV.deleteBtn.tag = i;
        [deleteV.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:deleteV];
        itemX += itemW + 7;
    }
    
    UILabel *countL = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - 75, 10, 60, 12)];
    countL.font = [UIFont fontWithName:@"PingFang SC" size:12];
    countL.textAlignment = NSTextAlignmentRight;
    countL.textColor = UIColorFromRGB(0x96ABB5);
    
    NSString *countStr = [NSString stringWithFormat:@"已选(%zd/3)", self.selectedRightDatas.count];
    NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:countStr];
    //获取要调整颜色的文字位置,调整颜色
    [hintString addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0X00BCCC) range:NSMakeRange(3, 1)];
    countL.attributedText = hintString;
    [self.topView addSubview:countL];
    
    self.topViewHeight.constant = topViewHeight;
    self.topViewHeight.constant = 70;
    self.topViewHeight.constant = topViewHeight;
}

- (void)deleteBtnClick:(UIButton *)btn {
    IndustryModel *job = [self.selectedRightDatas objectAtIndex:btn.tag];
    
    self.selectedRightDatas = [self deleteJobModel:job];
    [self setTopView];
    [self.rightTableView reloadData];
}

- (NSMutableArray *)deleteJobModel:(IndustryModel *)job {
    NSMutableArray *results = [NSMutableArray array];
    for (NSInteger i = 0; i < self.selectedRightDatas.count; i++) {
        IndustryModel *jobM = [self.selectedRightDatas objectAtIndex:i];
        if ([job.industryId isEqualToString:jobM.industryId]) {
        } else {
            [results addObject:jobM];
        }
    }
    return results;
}

- (NSMutableArray *)leftDatas {
    if (!_leftDatas) {
        _leftDatas = [NSMutableArray array];
    }
    return _leftDatas;
}

- (NSMutableArray *)rightDatas {
    if (!_rightDatas) {
        _rightDatas = [NSMutableArray array];
    }
    return _rightDatas;
}

- (NSMutableArray *)selectedRightDatas {
    if (!_selectedRightDatas) {
        _selectedRightDatas = [NSMutableArray array];
    }
    return _selectedRightDatas;
}

@end
